import { Button, Menu, Modal, Select, Popover, message } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';

import { fileDownload } from '@/utils/downExcel';

import {
  getSupplierList,
  updateOrSaveSupplier
} from './service.js';

import HeaderDropdown from '@/components/HeaderDropdown';
import { DownOutlined } from '@ant-design/icons';
import AuthComponent from '@/components/Authorized/AuthComponent';

import SupplierEdit from './components/SupplierEdit';

const MenuItem = Menu.Item;
const { confirm: ModalConfirm, info: ModalInfo } = Modal;
const { Option } = Select;

export default () => {

  const actionRef = useRef();
  const ref = useRef();

  const [height, controlH] = useState(300); // table高度
  const [isCollapse, controlC] = useState(true);

  const [categoryList, setCategoryList] = useState([]); // 供应商查询列表

  const [choiceSupplier, setChoiceSupplier] = useState(null);
  const [choiceSupplierShow, setChoiceSupplierShow] = useState(false);

  const { run: updateOrSaveSupplierRun } = useRequest(updateOrSaveSupplier, {
    manual: true,
    onSuccess: res => {
      message.success(choiceSupplierShow === 'add' ? '新增成功' : '编辑成功');
      setChoiceSupplierShow(false);
      actionRef.current.reload();
    }
  })

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 347);
    } else {
      controlH(document.body.clientHeight - 482);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isCollapse])

  useEffect(() => {
    !choiceSupplierShow && setChoiceSupplier(null);
  }, [choiceSupplierShow])

  // 查询标签树
  // const { data } = useRequest(getTree);
  const data = [];

  // 删除
  const deleteProduct = id => {
    ModalConfirm({
      title: '提示',
      content: '确认删除吗？',
      onOk: () => {
        runDelSaleProduct(id);
      }
    })
  }

  const beforeSearchSubmit = params => {
    return params;
  }

  // 操作菜单
  const overlayMenu = row => {
    return (
      <Menu>
        <MenuItem>
          {/* <AuthComponent authCode="serviceQuality.PassengerTag.delete"> */}
          <Button type="link">删除</Button>
          {/* </AuthComponent> */}
        </MenuItem>
      </Menu>
    )
  };

  const columns = [
    {
      title: '操作',
      dataIndex: 'id',
      hideInSearch: true,
      render: (_, row) => (
        <HeaderDropdown
          arrow={true}
          trigger={['hover']}
          overlay={() => overlayMenu(row)}
        >
          <Button type="link" onClick={() => { setChoiceSupplierShow('edit'); setChoiceSupplier(row); }}>
            {/* <AuthComponent authCode="serviceQuality.PassengerTag.update"> */}
            <span>编辑</span>
            {/* </AuthComponent> */}
            <DownOutlined />
          </Button>
        </HeaderDropdown>
      ),
    },
    {
      title: '供应商代码',
      dataIndex: 'supplierCode'
    },
    {
      title: '供应商名称',
      dataIndex: 'supplierName'
    },
    {
      title: '供应商邮箱',
      dataIndex: 'supplierEmail',
      render: (_, row) => {
        return (
          <Popover content={_}>
            <span className={styles.emailStyles}>{_}</span>
          </Popover>
        )
      }
    }
  ];

  const save = e => {
    console.log(e);
    updateOrSaveSupplierRun({
      ...choiceSupplier,
      supplierName: e.supplierName,
      supplierState: e.supplierState,
      currency: e.currency,
      supplierEmail: (e.emails.filter(item => item).map(item => item + '.com')).join(',')
    });
  }

  return (
    <>
      <Modal
        title={choiceSupplierShow === 'add' ? '新增' : '编辑'}
        visible={Boolean(choiceSupplierShow)}
        destroyOnClose="true"
        maskClosable="true"
        onCancel={() => setChoiceSupplierShow(false)}
        footer={null}
      >
        {
          choiceSupplierShow &&
          <SupplierEdit
            choiceSupplier={choiceSupplier}
            save={save}
            onCancel={() => setChoiceSupplierShow(false)}
          />}
      </Modal>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.compactTable}
        headerTitle={
          <div className="pull-right">
            {/* <AuthComponent authCode="onBoardAuxiliaryBattalions.AuxiliaryGood.saveSaleProduct"> */}
            {/* <Button type="primary" onClick={clickExportListLabelByIds} className={styles.buttonRight}>导出</Button> */}
            <Button type="primary" onClick={() => setChoiceSupplierShow('add')}>新增</Button>
            {/* </AuthComponent> */}
          </div>
        }
        request={params => {
          // setSelectedRowKeys([]);
          // setSelectedRows([]);
          return getSupplierList(params);
        }}
        tableAlertRender={false}
        columns={columns}
        options={{}}
        beforeSearchSubmit={beforeSearchSubmit}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
        }}
        scroll={{ x: 900, y: height }}
        search={{
          onCollapse: val => {
            controlC(val)
          }
        }}
      >
      </ProTable>
    </>
  )
}
